package com.dev;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.fb.FileBrowserPage;
import com.log;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
public class QueryPaste extends LinearLayout implements OnClickListener{
	WindowManager.LayoutParams wlp=new WindowManager.LayoutParams();
	File destination;
	LinearLayout titlebar;
	LinearLayout bottombar;
	TextView title;
	TextView msg;
	TextButton it0,it1,it2;
	IconViewClose ivc;
	LayoutParams tblp;
	CheckableItem ci1,ci2;
	ShowSoftInput ssi;
	EditText editor;
	int ctrl=0;
	MainActivity ma;
	public QueryPaste(MainActivity ma){
		super(ma);
		this.ma=ma;
		setOrientation(VERTICAL);
		setWillNotDraw(false);
		tblp=new LayoutParams(-1,ma.dialogTitleBarHeight);
		title=new TextView(ma);
		title.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
		title.setGravity(Gravity.CENTER_VERTICAL);
		title.setTextColor(0xff7f7f7f);
		title.setText("文件已存在：");
		title.setPadding(9,0,0,0);
		ivc=new IconViewClose(ma);
		ivc.setOnClickListener(this);
		ssi=new ShowSoftInput(ma);
		ssi.setOnClickListener(this);
		titlebar=new LinearLayout(ma){
			@Override
			public void onDraw(Canvas c){
				super.onDraw(c);
				Paint p=new Paint();
				p.setColor(FileBrowserPage.borderColor);
				c.drawRect(0,getHeight()-FileBrowserPage.borderWidth,getWidth(),getHeight(),p);
			}
		};
		titlebar.setWillNotDraw(false);
		titlebar.setOrientation(HORIZONTAL);
		titlebar.addView(title,new LayoutParams(0,-1,1));
		titlebar.addView(ssi);
		titlebar.addView(ivc);
		editor=new EditText(ma){
			public void onDraw(Canvas cvs){
				super.onDraw(cvs);
				Paint p=new Paint();
				p.setStrokeWidth(3);
				if(isFocused()){
					p.setColor(0xffff0000);
				}else{
					p.setColor(0xff777777);
				}
				int ver=getHeight()/2+(int)(getTextSize()*0.7);
				cvs.translate(getScrollX(),getScrollY());
				cvs.drawLine(getPaddingLeft(),ver,getRight()-getPaddingRight(),ver,p);
			}
		};
		//editor.addTextChangedListener(this);
		editor.setTypeface(Typeface.MONOSPACE);
		editor.setTextSize(TypedValue.COMPLEX_UNIT_DIP,14);
		editor.setTextColor(0xff000000);
		editor.setGravity(Gravity.CENTER_VERTICAL);
		editor.setBackgroundColor(0x00ffffff);
		editor.setPadding(10,0,10,0);
		editor.setSingleLine();
		msg=new TextView(ma);
		msg.setTextSize(TypedValue.COMPLEX_UNIT_DIP,13);
		msg.setTypeface(Typeface.MONOSPACE);
		msg.setTextColor(0xff000000);
		msg.setPadding(9,9,9,9);
		msg.setTextColor(0xffff0000);
		it0=new TextButton(ma,"覆盖");
		it0.setOnClickListener(this);
		it0.borderColor=FileBrowserPage.borderColor;
		it0.borderWidth=FileBrowserPage.borderWidth;
		it0.borderTop=true;
		it1=new TextButton(ma,"重命名");
		it1.setOnClickListener(this);
		it1.borderColor=FileBrowserPage.borderColor;
		it1.borderWidth=FileBrowserPage.borderWidth;
		it1.borderTop=true;
		it2=new TextButton(ma,"跳过");
		it2.setOnClickListener(this);
		it2.borderColor=FileBrowserPage.borderColor;
		it2.borderWidth=FileBrowserPage.borderWidth;
		it2.borderTop=true;
		ci1=new CheckableItem(ma,"重命名源文件");
		ci1.border=false;
		ci1.setOnClickListener(this);
		ci2=new CheckableItem(ma,"为后续冲突执行此操作");
		ci2.border=false;
		ci2.setOnClickListener(this);
		ci2.box.setSelected(true);
		bottombar=new LinearLayout(ma);
		bottombar.setOrientation(HORIZONTAL);
		LinearLayout.LayoutParams itlp=new LinearLayout.LayoutParams(0,-1,1);
		bottombar.addView(it0,itlp);
		bottombar.addView(it1,itlp);
		bottombar.addView(it2,itlp);
		addView(titlebar,-1,(int)(28*ma.dp));
		addView(editor,-1,(int)(33*ma.dp));
		addView(ci1,-1,(int)(30*ma.dp));
		addView(ci2,-1,(int)(30*ma.dp));
		addView(bottombar,-1,(int)(30*ma.dp));
	}
	int unpaste=0;
	int undelete=0;
	FileBrowserPage fbp;
	public void startPaste(FileBrowserPage fbp,File destination){
		this.destination=destination;
		this.fbp=fbp;
		if(destination.canWrite()){
			unpaste=0;
			undelete=0;
			paste();
		}else{
			Toast.makeText(ma,"不可写",0).show();
		}
	}
	void paste(){
		for(int size=ma.fileClipBoard.size();true;size--){
			if(size>0){
				FileClipData fcd=ma.fileClipBoard.get(0);
				File from=fcd.f;
				String filename=from.getName();
				File to=new File(destination,filename);
				if(from.getParentFile().equals(destination))continue;
				if(fcd.move){//剪贴
					if(to.exists()){
						ctrl=0;
						show();
						break;
					}else if(from.renameTo(to)){
						ma.fileClipBoard.remove(0);
					}else{//可能隔着文件系统所以导致失败，复制后删除原文件
						try{
							cut(from,destination);
						}catch(Exception e){
							log.alert("On cut file to given dir",e.toString());
						}
						ma.fileClipBoard.remove(0);
					}
				}else if(to.exists()){//复制
					ctrl=0;
					show();
				}else{
					try{
						copy(from,destination);
					}catch(Exception e){
						log.alert("On copy file to given dir",e.toString()+"\nfrom:"+from.getAbsolutePath()+"\nto:"+to.getAbsolutePath());
					}
					ma.fileClipBoard.remove(0);
				}
			}else{//no file can paste
				if(unpaste>0||undelete>0){
					log.alert("出错",unpaste+"个项目未复制\n"+undelete+"个项目未删除");
					if(fbp.currentDirectory!=null){
						File list[]=fbp.currentDirectory.listFiles();
						fbp.setWillShow(list);
					}
				}else{
					if(fbp.currentDirectory!=null){
						File list[]=fbp.currentDirectory.listFiles();
						fbp.setWillShow(list);
						Toast.makeText(ma,"已粘贴",0).show();
					}
				}
				fbp.ivPaste.setVisibility(View.GONE);
				dismiss();
				break;
			}
		}
	}
	private void show(){
		if(ctrl==0){
			FileClipData fcd=ma.fileClipBoard.get(0);
			File f=fcd.f;
			msg.setText(f.getAbsolutePath());
			String f_name=f.getName();
			int ii=f_name.lastIndexOf('.');
			if(ii>0){
				for(int i=1;i<100;i++){
					String name=f_name.substring(0,ii)+i+f_name.substring(ii);
					File fi=new File(destination,name);
					if(!fi.exists()){
						editor.setText(name);
						break;
					}
				}
			}else{
				for(int i=1;i<100;i++){
					String name=f_name+i;
					File fi=new File(destination,name);
					if(!fi.exists()){
						editor.setText(name);
						break;
					}
				}
			}
		}
		wlp.width=ma.gui.getWidth()*4/5;
		wlp.height=-2;
		ma.wm.addView(this,wlp);
	}
	void dismiss(){
		if(isAttachedToWindow()){
			ma.wm.removeView(this);
		}
	}
	void cut(File from,File dir)throws Exception{
		File willcreate=new File(dir,from.getName());
		if(from.isDirectory()){
			willcreate.mkdir();
			if(willcreate.exists()){
				File fs[]=from.listFiles();
				for(File f:fs){
					cut(f,willcreate);
				}
				if(!from.delete())undelete++;
			}else{
				unpaste++;
			}
		}else if(willcreate.exists()){
			if(willcreate.isFile()){
				FileInputStream fis=new FileInputStream(from);
				FileOutputStream fos=new FileOutputStream(willcreate,false);
				byte[] buffer=new byte[1024];
				int len=fis.read(buffer);
				while(len>0){
					fos.write(buffer,0,len);
					len=fis.read(buffer);
				}
				fis.close();
				fos.close();
				if(!from.delete())undelete++;
			}
		}else if(willcreate.createNewFile()){
			FileInputStream fis=new FileInputStream(from);
			FileOutputStream fos=new FileOutputStream(willcreate,false);
			byte[] buffer=new byte[1024];
			int len=fis.read(buffer);
			while(len>0){
				fos.write(buffer,0,len);
				len=fis.read(buffer);
			}
			fis.close();
			fos.close();
			if(!from.delete())undelete++;
		}else{
			unpaste++;
		}
	}
	void copy(File from,File dir)throws Exception{
		File willcreate=new File(dir,from.getName());
		if(from.isDirectory()){
			willcreate.mkdir();
			if(willcreate.exists()){
				File fs[]=from.listFiles();
				for(File f:fs){
					copy(f,willcreate);
				}
			}
		}else if(willcreate.exists()){
			if(willcreate.isFile()){
				FileInputStream fis=new FileInputStream(from);
				FileOutputStream fos=new FileOutputStream(willcreate,false);
				byte[] buffer=new byte[1024];
				int len=fis.read(buffer);
				while(len>0){
					fos.write(buffer,0,len);
					len=fis.read(buffer);
				}
				fis.close();
				fos.close();
			}else{
				unpaste++;
			}
		}else if(willcreate.createNewFile()){
			//log.alert(from.toString());
			FileInputStream fis=new FileInputStream(from);
			FileOutputStream fos=new FileOutputStream(willcreate,false);
			byte[] buffer=new byte[1024];
			int len=fis.read(buffer);
			while(len>0){
				fos.write(buffer,0,len);
				len=fis.read(buffer);
			}
			fis.close();
			fos.close();
		}else{
			unpaste++;
		}
	}
	void cutByOverride(File from,File dir)throws Exception{
		File willcreate=new File(dir,from.getName());
		if(from.isDirectory()){
			willcreate.mkdir();
			if(willcreate.exists()){
				File fs[]=from.listFiles();
				for(File f:fs){
					cutByOverride(f,willcreate);
				}
				if(!from.delete())undelete++;
			}else{
				unpaste++;
			}
		}else if(willcreate.exists()){
			if(willcreate.isFile()){
				if(willcreate.canWrite()){
					FileInputStream fis=new FileInputStream(from);
					FileOutputStream fos=new FileOutputStream(willcreate,false);
					byte[] buffer=new byte[1024];
					int len=fis.read(buffer);
					while(len>0){
						fos.write(buffer,0,len);
						len=fis.read(buffer);
					}
					fis.close();
					fos.close();
					if(!from.delete())undelete++;
				}else{
					unpaste++;
				}
			}else unpaste++;
		}else if(willcreate.createNewFile()){
			FileInputStream fis=new FileInputStream(from);
			FileOutputStream fos=new FileOutputStream(willcreate,false);
			byte[] buffer=new byte[1024];
			int len=fis.read(buffer);
			while(len>0){
				fos.write(buffer,0,len);
				len=fis.read(buffer);
			}
			fis.close();
			fos.close();
			if(!from.delete())undelete++;
		}else{
			unpaste++;
		}
	}
	void copyByOverride(File from,File dir)throws Exception{
		File willCreate=new File(dir,from.getName());
		if(from.isDirectory()){
			willCreate.mkdir();
			if(willCreate.exists()){
				File[] fs=from.listFiles();
				for(File f:fs){
					copyByOverride(f,willCreate);
				}
			}else{
				unpaste++;
			}
		}else if(willCreate.exists()){
			if(willCreate.isFile()){
				FileInputStream fis=new FileInputStream(from);
				FileOutputStream fos=new FileOutputStream(willCreate,false);
				byte[] buffer=new byte[1024];
				int len=fis.read(buffer);
				while(len>0){
					fos.write(buffer,0,len);
					len=fis.read(buffer);
				}
				fis.close();
				fos.close();
			}else unpaste++;
		}else if(willCreate.createNewFile()){
			FileInputStream fis=new FileInputStream(from);
			FileOutputStream fos=new FileOutputStream(willCreate,false);
			byte[] buffer=new byte[1024];
			int len=fis.read(buffer);
			while(len>0){
				fos.write(buffer,0,len);
				len=fis.read(buffer);
			}
			fis.close();
			fos.close();
		}else{
			unpaste++;
		}
	}
	@Override
	public void onClick(View v){
		if(v==ci1){
			if(ci1.box.isSelected()){
				ci1.box.setSelected(false);
				ci2.box.setSelected(true);
			}else{
				ci1.box.setSelected(true);
				ci2.box.setSelected(false);
			}
		}else if(v==ci2){
			if(ci2.box.isSelected()){
				ci2.box.setSelected(false);
				ci1.box.setSelected(true);
			}else{
				ci2.box.setSelected(true);
				ci1.box.setSelected(false);
			}
		}else if(v==ivc){
			dismiss();
		}else if(v==it0){//覆盖
			FileClipData fcd=ma.fileClipBoard.get(0);
			File from=fcd.f;
			if(!from.getParentFile().equals(destination)){
				if(fcd.move){//delete src file after copied
					try{
						cutByOverride(from,destination);
					}catch(Exception e){
						log.alert("On cut file to new dir",e.toString());
					}
					ma.fileClipBoard.remove(0);
					paste();
				}else{
					try{
						copyByOverride(from,destination);
					}catch(Exception e){
						log.alert("On copy file to new dir",e.toString());
					}
				}
			}
			ma.fileClipBoard.remove(0);
			paste();
		}else if(v==it1){//重命名
			FileClipData fcd=ma.fileClipBoard.get(0);
			File file=fcd.f;
			String file_name=file.getName();
			File dst=new File(destination,file_name);
            String editor_name;
            if(editor.length()>0){
                editor_name=editor.getEditableText().toString();
            }else{
                editor_name=editor.getHint().toString();
            }
            File f1=new File(destination,editor_name);
            if(f1.exists()){
                Toast.makeText(ma,"文件已在目标目录中存在",0).show();
                return;
            }
            if(ci1.box.isSelected()){
                dst=f1;
            }else{
                File f2=new File(destination,file_name);
                if(!f2.renameTo(f1)){
                    Toast.makeText(ma,"重命名失败",0).show();
                }
            }
			if(dst.canRead()){
				if(fcd.move){
					if(!file.renameTo(dst)){
						unpaste++;
					}
				}else{
					try{
						FileInputStream fis=new FileInputStream(file);
						FileOutputStream fos=new FileOutputStream(dst,false);
						byte[] buffer=new byte[1024];
						int len=fis.read(buffer);
						while(len>=0){
							fos.write(buffer,0,len);
							len=fis.read(buffer);
						}
						fis.close();
						fos.close();
					}catch(Exception e){
						log.alert(e.toString());
					}
				}
				ma.fileClipBoard.remove(0);
				paste();
			}else{
				unpaste++;
				ma.fileClipBoard.remove(0);
				paste();
			}
		}else if(v==it2){//跳过
			if(ctrl==0){
				ma.fileClipBoard.remove(0);
				paste();
			}
		}else if(v==ssi){
			if(editor.requestFocus()){
				ma.imm.toggleSoftInput(0,0);
			}
		}
	}
	@Override
	protected void onDraw(Canvas canvas){
		super.onDraw(canvas);
		Paint p=new Paint();
		p.setColor(FileBrowserPage.borderColor);
		canvas.drawColor(0xffffffff);
		canvas.drawRect(0,0,FileBrowserPage.borderWidth,getHeight(),p);
		canvas.drawRect(0,0,getWidth(),FileBrowserPage.borderWidth,p);
		canvas.drawRect(getWidth()-FileBrowserPage.borderWidth,0,getWidth(),getHeight(),p);
		canvas.drawRect(0,getHeight()-FileBrowserPage.borderWidth,getWidth(),getHeight(),p);
	}
}
